package ru.spb.osll.myfit.client.widget;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.user.client.ui.TextBox;

/**
 * User: Alexander Opeykin (alexander.opeykin@gmail.com)
 * Date: 5/14/12
 * Time: 1:44 PM
 */
public class WatermarkedTextBox extends TextBox implements BlurHandler, FocusHandler {
  private String m_watermark = "";
  private String m_watermarkStyle = "";
  private boolean m_watermarkEnabled = false;

  public void setWatermark(String watermark) {
    m_watermark = watermark;
    addBlurHandler(this);
    addFocusHandler(this);
    enableWatermark();
  }

  public void setWatermarkStyle(String watermarkStyle) {
    m_watermarkStyle = watermarkStyle;
    enableWatermark();
  }

  @Override
  public void setText(String text) {
    super.setText(text);
    enableWatermark();
  }

  @Override
  public String getText() {
    if (m_watermarkEnabled) {
      return "";
    } else {
      return super.getText();
    }
  }

  @Override
  public void onBlur(BlurEvent blurEvent) {
    enableWatermark();
  }

  @Override
  public void onFocus(FocusEvent focusEvent) {
    disableWatermark();
  }


  protected void enableWatermark() {
    if (getText().length() == 0) {
      addStyleName(m_watermarkStyle);
      super.setText(m_watermark);
      m_watermarkEnabled = true;
    }
  }

  protected void disableWatermark() {
    if (m_watermarkEnabled) {
      removeStyleName(m_watermarkStyle);
      super.setText("");
      m_watermarkEnabled = false;
    }
  }
}
